//
//  CWJavaScriptApi.m
//  CWDevelop
//
//  Created by LittoCats on 7/9/14.
//  Copyright (c) 2014 Littocats. All rights reserved.
//

#import "CWJavaScriptApi.h"
#import "CWCore.h"

#import <objc/message.h>

@implementation CWJavaScriptApi

+ (void)analyseAction:(NSMutableDictionary *)action
{
    //analyse javascript context
    CWJavaScriptContext *jsContext = [NSObject findInstanceWithId:action[kJavaScriptContextKey]];
    //analyse callBack function
    CWScriptFunction *jsFunction = [CWScriptFunction functionWithFunctionScript:action[kJavaScriptCallBackFunctionKey] context:jsContext._id];
    
    [action setObject:jsContext forKey:kJavaScriptContextKey];
    [action setObject:jsFunction forKey:kJavaScriptCallBackFunctionKey];
}

#pragma mark- callNativeMethod
void dispatch_jsapi(NSString *method, id params, NSString *callBackId, NSMutableDictionary *action){
    [action setObject:callBackId forKey:kJavaScriptCallBackFunctionKey];
    Class domain = NSClassFromString([NSString stringWithFormat:@"CWJavaScriptApi%@",
                                      action[kJavaScriptAPIKey] ? [action[kJavaScriptAPIKey] capitalizedString] : @""]);
    
    if (!domain || ![domain respondsToSelector:@selector(analyseAction:)])
        CWLog(@"[CWJavaScriptAPI] error : domain< %@ > is not exist .",action[kJavaScriptAPIKey]);
    
    objc_msgSend(domain, @selector(analyseAction:), action);
    
    SEL api = NSSelectorFromString([NSString stringWithFormat:@"%@:action:",method]);
    if ([domain respondsToSelector:api])
        objc_msgSend(domain, api, params, action);
    else
        CWLog(@"[CWJavaScriptAPI] error : api< %@ > is not exist in domain < %@ > .",method,action[kJavaScriptAPIKey]);
}

#pragma mark- utilies
@end
